package com.cjz.tool.qr;

import javax.swing.SwingUtilities;

import com.cjz.tool.qr.config.Setting;
import com.cjz.tool.qr.pojo.ParseResult;
import com.cjz.tool.qr.ui.MainFrame;
import com.cjz.tool.qr.utils.Util;

import craky.util.Config;
import craky.util.UIUtil;

public class QRreader {

	public static void main(String[] args) {
		System.setProperty("sun.java2d.noddraw", "true");
		UIUtil.setPopupMenuConsumeEventOnClose(false);
		UIUtil.initToolTipForSystemStyle();
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				new QRreader();
			}
		});
	}

	static QRreader qrReader;

	Config config;
	ParseResult result;
	MainFrame mainFrame;

	public MainFrame getMainFrame() {
		return mainFrame;
	}

	public synchronized static QRreader getInstance() {
		return qrReader;
	}

	private QRreader() {
		qrReader = this;
		loadSetting();
		start();
	}

	public Config getConfig() {
		return config;
	}

	public void saveConfig() {
		QRreader.getInstance().getConfig().setPropertie(Setting.ALWAYS_TOP_WHEN_RUNNING, String.valueOf(Setting.alwaysTopWhenRunning));
		QRreader.getInstance().getConfig().setPropertie(Setting.HIDE_SELF_WHEN_CAPTURE, String.valueOf(Setting.hideSelfWhenCapture));
		QRreader.getInstance().getConfig().setPropertie(Setting.MIN_TO_TRAY, String.valueOf(Setting.minToTray));
		QRreader.getInstance().getConfig().setPropertie(Setting.AUTO_COPY_TO_CLIPBOARD, String.valueOf(Setting.autoCopyResult));
		QRreader.getInstance().getConfig().saveConfig();
	}

	private void loadSetting() {
		config = new Config(Setting.CONFIG_PATH);
		Setting.alwaysTopWhenRunning = Boolean.parseBoolean(config.getProperty(Setting.ALWAYS_TOP_WHEN_RUNNING, String.valueOf(true)));
		Setting.hideSelfWhenCapture = Boolean.parseBoolean(config.getProperty(Setting.HIDE_SELF_WHEN_CAPTURE, String.valueOf(true)));
		Setting.minToTray = Boolean.parseBoolean(config.getProperty(Setting.MIN_TO_TRAY, String.valueOf(false)));
		Setting.autoCopyResult = Boolean.parseBoolean(config.getProperty(Setting.AUTO_COPY_TO_CLIPBOARD, String.valueOf(true)));
	}

	private void start() {
		mainFrame = new MainFrame();
		mainFrame.setVisible(true);
	}

	public void copy2Clipboard() {
		if (result != null && result.isSuccess()) {
			Util.copyText2Clipboard(result.getResult());
		} else {
			Util.copyText2Clipboard("");
		}
	}

	public void exit() {
		System.exit(0);
	}

	public ParseResult getResult() {
		return result;
	}

	public void setResult(ParseResult result) {
		this.result = result;
	}
}
